package com.sduept.nwld.dataserver.controller.ledger;

import com.sduept.bigdata.web.jsf.controller.AbstractController;
import com.sduept.cim.ledger.manager.ManagementUnitMaintainManager;
import com.sduept.cim.ledger.manager.SubstationLedgerManager;
import com.sduept.cim.ledger.model.ManagementUnitDict;
import com.sduept.cim.ledger.model.PrimaryEquipmentLedger;
import com.sduept.cim.ledger.model.SubstationLedger;
import com.sduept.cim.model.core.Substation;
import com.sduept.nwld.dataserver.manager.cim.CimManager;
import com.sduept.utils.PingYinUtil;
import org.apache.commons.lang3.StringUtils;
import org.primefaces.event.SelectEvent;
import org.primefaces.event.TabChangeEvent;
import org.springframework.beans.factory.annotation.Autowired;

import javax.annotation.PostConstruct;
import javax.faces.view.ViewScoped;
import javax.inject.Named;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

/**
 * 管理单位维护Controller
 * @author xu
 *
 */
@Named
@ViewScoped
public class ManagementUnitMaintainController extends AbstractController{

	private static final long serialVersionUID = -7987708087465788436L;
    
	@Autowired
	private ManagementUnitMaintainManager primaryM;
	@Autowired
	private SubstationLedgerManager stationLedgerM;
	@Autowired
	private CimManager cimM;
	
	
	
	private List<PrimaryEquipmentLedger> aclineModel;
	private List<PrimaryEquipmentLedger> dclineModel;
	private List<PrimaryEquipmentLedger> busbarModel;
	private List<PrimaryEquipmentLedger> transModel;
	private List<PrimaryEquipmentLedger> breakerModel;
	private List<PrimaryEquipmentLedger> compensatorModel;
	private List<PrimaryEquipmentLedger> substationModel;
	private List<PrimaryEquipmentLedger> selectedLedgerList = new ArrayList<PrimaryEquipmentLedger>();
	private PrimaryEquipmentLedger editLedger = new PrimaryEquipmentLedger();
	private String selectdStandVolLevel = "500";  //电压等级默认为500
	private String equipmentName = null; // 设备名称
	private String tabTitle = "变电站";//不同的tab页
	private boolean tabTitleStatus = false;
	private String subStation = null; // 所属变电站
	private boolean dispatchStatus;
	private SubstationLedger queryLedger = new SubstationLedger();
	
	@PostConstruct
	public void init() {
		initTabTitleStatus();
		initTable();
	}


    /**
     * 初始化各个table数据
     */
	private void initTable() {
		if("交流线路".equals(tabTitle)) initAclineTable();;;//
		if("直流线路".equals(tabTitle)) initDclineTable();//
		if("母线".equals(tabTitle)) initBusbarSectionTable();//
		if("变压器".equals(tabTitle)) initPowerTransformerTable();//
		if("断路器".equals(tabTitle)) initBreakerTable();//
		if("电抗器".equals(tabTitle)) initCompensatorTable();
		if("变电站".equals(tabTitle)) initSubstationTable();
	}
     private void initSubstationTable() {
    	 substationModel = primaryM.findEquipmentDataByVoltageAndStationAndNameAndTypeAndUnitName(selectdStandVolLevel,subStation, null, "变电站",queryLedger);//变电站查询		
     }

   
     
	/**
      * 初始化电抗器table
      */
    private void initCompensatorTable() {
    	compensatorModel = primaryM.findEquipmentDataByVoltageAndStationAndNameAndTypeAndUnitName(selectdStandVolLevel,null, subStation, "电抗器",queryLedger);
	}

    /**
     * 初始化断路器table
     */
	private void initBreakerTable() {
		breakerModel = primaryM.findEquipmentDataByVoltageAndStationAndNameAndTypeAndUnitName(selectdStandVolLevel,null, subStation, "断路器",queryLedger);
	}

    /**
     * 初始化变压器table
     */
	private void initPowerTransformerTable() {
		transModel = primaryM.findEquipmentDataByVoltageAndStationAndNameAndTypeAndUnitName(selectdStandVolLevel,null, subStation, "变压器",queryLedger);
	}

    /**
     * 初始化母线table
     */
	private void initBusbarSectionTable() {
		busbarModel = primaryM.findEquipmentDataByVoltageAndStationAndNameAndTypeAndUnitName(selectdStandVolLevel,null, subStation,"母线",queryLedger);
	}


	/**
          * 初始化直流线table
     */
	private void initDclineTable() { 
		dclineModel = primaryM.findEquipmentDataByVoltageAndStationAndNameAndTypeAndUnitName(selectdStandVolLevel, equipmentName,null,"直流线",queryLedger);
	}

    /**
     * 初始化交流线table
     */
	private void initAclineTable() {
		aclineModel = primaryM.findEquipmentDataByVoltageAndStationAndNameAndTypeAndUnitName(selectdStandVolLevel, equipmentName,null,"交流线",queryLedger);
	}


	public void query() {
		selectedLedgerList = new ArrayList<>();
		if("交流线路".equals(tabTitle)) {
			initAclineTable();
		}else {
			initTable();
		}
		
		
	}
	
	public void reset() {
		selectdStandVolLevel="500";
		subStation = null;
		equipmentName = null;
		dispatchStatus = false;
		queryLedger = new SubstationLedger();
		selectedLedgerList = new ArrayList<>();
		initTable();
	}
	
	
	public void onTabChange(TabChangeEvent event) {
		tabTitle = event.getTab().getTitle();
		selectedLedgerList = new ArrayList<>();
		initTabTitleStatus();
		initTable();
    }
	
	/**
	 * 变电站名称
	 * @param query
	 * @return
	 */
	public List<String> complateStation(String query) {
		List<Substation> allStations = cimM.findUsedAndUnUsedStations();
		List<String> names = new ArrayList<String>();
		names.add("全部");
		if (Pattern.matches("[a-z]{1,}", query)) {
			for (Substation station : allStations) {
				String nameHead = PingYinUtil.getPingYinHeader(station
						.getName());
				if (nameHead.toLowerCase().contains(query)) {
					names.add(station.getName());
				}
			}
		} else {
			for (Substation station : allStations) {
				if (station.getName().contains(query)) {
					names.add(station.getName());
				}
			}
		}
		return names;
	}
	
	private void initTabTitleStatus() {
		if("交流线路".equals(tabTitle) || "直流线路".equals(tabTitle)) {
			tabTitleStatus = false;
		}else {
			tabTitleStatus = true;
		}
	}

	public void preEdit() {
		if(selectedLedgerList.size()==1){
			setEditLedger(selectedLedgerList.get(0));
		} 
	}
	
	/**
	 * 保存到ledger表 加上设备类型
	 */
	public void save() {
		if(editLedger.getId()==null) {
			addErrorMessage("保存失败！");
			return;
		}
		if(editLedger.getEquipmentType()==null) {
			editLedger.setEquipmentType(tabTitle);
		}
		if("变电站".equals(tabTitle)) {//编辑变电站 在primaryledger表和substationledger表同存一份
			editLedger.setName(editLedger.getSubName());
			createOrUpdateSubstationLedger(editLedger);
		}
		try {
			primaryM.createOrUpdate(editLedger);
			addSuccessMessage("保存成功！");
		} catch (Exception e) {
			addErrorMessage("保存失败!");
		}
		selectedLedgerList = new ArrayList<>();
		initTable();
	}
	
	/**
	 * 存到substationLedger表内
	 * @param editLedger
	 */
	private void createOrUpdateSubstationLedger(PrimaryEquipmentLedger editLedger) {
        SubstationLedger subLedger =stationLedgerM.findSubstationLedger(editLedger.getCimId());
        if(subLedger==null) {
        	subLedger=new SubstationLedger();
        	subLedger.setId(editLedger.getId());
        }
         subLedger.setAssetOwner(editLedger.getAssetOwner());
		 subLedger.setCimId(editLedger.getCimId());
		 subLedger.setDispatchUnit(editLedger.getDispatchUnit());
	     subLedger.setDispatchUnitId(editLedger.getDispatchUnitId());
		 subLedger.setEquipmentType(editLedger.getEquipmentType());
		 subLedger.setMaintenanceUnit(editLedger.getMaintenanceUnit());
		 subLedger.setMaintenanceUnitId(editLedger.getMaintenanceUnitId());
		 subLedger.setName(editLedger.getName());
		 subLedger.setPrimaryEquipmentScope(editLedger.getPrimaryEquipmentScope());
		 subLedger.setPrimaryEquipmentScopeId(editLedger.getPrimaryEquipmentScopeId());
		 subLedger.setPrimaryEquipmentScopeRemark(editLedger.getPrimaryEquipmentScopeRemark());
		 subLedger.setSecondaryEquipmentScope(editLedger.getSecondaryEquipmentScope());
		 subLedger.setSecondaryEquipmentScopeId(editLedger.getSecondaryEquipmentScopeId());
		 subLedger.setSecondaryEquipmentScopeRemark(editLedger.getSecondaryEquipmentScopeRemark());
		 subLedger.setUnitType(editLedger.getUnitType());
		try {
			stationLedgerM.createOrUpdateSubstationLedger(subLedger);
		}catch (Exception e){
			addErrorMessage("更新失败");
		}
	}


	/**
	 * 从ledger表删除
	 */
	public void delete() {
		List<String> idList=primaryM.findAllPrimaryEquipmentLedgerId();
		for (PrimaryEquipmentLedger select : selectedLedgerList) {
			if(select.getId()!=null&&idList.contains(select.getId())) {
				try {
					primaryM.delete(select.getId()); 
					addSuccessMessage("删除成功！");
				} catch (Exception e) {
					addErrorMessage("删除失败!");
				}
			}else {
				addErrorMessage("无法删除原始cim数据！");
			}
		}
		selectedLedgerList = new ArrayList<>();
		initTable();
	} 
	/**
	 * 选择调度部门后，设置PrimaryEquipmentLedger的对应值
	 * @param event
	 */
	public void onDesorgDepartChosen(SelectEvent event) {
		ManagementUnitDict dept = (ManagementUnitDict) event.getObject();
		editLedger.setDispatchUnit(dept.getName());
		editLedger.setDispatchUnitId(dept.getId());
	}
	
	/**
	 * 选择一次设备检修范围
	 * @param event
	 */
	public void onPrimaryScopeChosen(SelectEvent event) {
		ManagementUnitDict dept = (ManagementUnitDict) event.getObject();
		editLedger.setPrimaryEquipmentScope(dept.getName());
	}
	/**
	 * 选择二次设备检修范围
	 * @param event
	 */
	public void onSecondryScopeChosen(SelectEvent event) {
		ManagementUnitDict dept = (ManagementUnitDict) event.getObject();
		editLedger.setSecondaryEquipmentScope(dept.getName());
	}
	
	/**
	 * 选择运维部门后，设置PrimaryEquipmentLedger的对应值
	 * @param event
	 */
	public void onOpDepartChosen(SelectEvent event) {
		ManagementUnitDict dept = (ManagementUnitDict) event.getObject();
		editLedger.setMaintenanceUnit(dept.getName());
		editLedger.setMaintenanceUnitId(dept.getId());
		if(dept.getName().contains("超高压")) {
			editLedger.setUnitType("超高压分局");
		} else if (dept.getName().contains("供电局")) {
			editLedger.setUnitType("供电局");
		} else if (dept.getName().contains("电厂")) {
			editLedger.setUnitType("发电厂");
		} else {
			editLedger.setUnitType(null);
		}
	}
	
	
	public void dispatchQuery() {
		if(!"交流线路".equals(tabTitle)) {
			return;
		}
		initAclineTable();
		if(dispatchStatus==true) {//只显示未关联的
			aclineModel = aclineModel.stream().filter(PrimaryEquipmentLedger -> StringUtils.isBlank(PrimaryEquipmentLedger.getDispatchUnit()))
					                 .collect(Collectors.toList());
		}else {//显示关联的
			aclineModel = aclineModel.stream().filter(PrimaryEquipmentLedger -> StringUtils.isNotBlank(PrimaryEquipmentLedger.getDispatchUnit()))
	                 .collect(Collectors.toList());
		}
		
	}
	
	
	
	public String getSelectdStandVolLevel() {
		return selectdStandVolLevel;
	}
	

	public void setSelectdStandVolLevel(String selectdStandVolLevel) {
		this.selectdStandVolLevel = selectdStandVolLevel;
	}


	public String getEquipmentName() {
		return equipmentName;
	}


	public void setEquipmentName(String equipmentName) {
		this.equipmentName = equipmentName;
	}


	public String getTabTitle() {
		return tabTitle;
	}


	public void setTabTitle(String tabTitle) {
		this.tabTitle = tabTitle;
	}


	public boolean isTabTitleStatus() {
		return tabTitleStatus;
	}


	public void setTabTitleStatus(boolean tabTitleStatus) {
		this.tabTitleStatus = tabTitleStatus;
	}


	public String getSubStation() {
		return subStation;
	}


	public void setSubStation(String subStation) {
		this.subStation = subStation;
	}


	

	public List<PrimaryEquipmentLedger> getAclineModel() {
		return aclineModel;
	}


	public void setAclineModel(List<PrimaryEquipmentLedger> aclineModel) {
		this.aclineModel = aclineModel;
	}


	public List<PrimaryEquipmentLedger> getDclineModel() {
		return dclineModel;
	}


	public void setDclineModel(List<PrimaryEquipmentLedger> dclineModel) {
		this.dclineModel = dclineModel;
	}


	public List<PrimaryEquipmentLedger> getBusbarModel() {
		return busbarModel;
	}


	public void setBusbarModel(List<PrimaryEquipmentLedger> busbarModel) {
		this.busbarModel = busbarModel;
	}


	public List<PrimaryEquipmentLedger> getTransModel() {
		return transModel;
	}


	public void setTransModel(List<PrimaryEquipmentLedger> transModel) {
		this.transModel = transModel;
	}


	public List<PrimaryEquipmentLedger> getBreakerModel() {
		return breakerModel;
	}


	public void setBreakerModel(List<PrimaryEquipmentLedger> breakerModel) {
		this.breakerModel = breakerModel;
	}
	public List<PrimaryEquipmentLedger> getCompensatorModel() {
		return compensatorModel;
	}
	public void setCompensatorModel(List<PrimaryEquipmentLedger> compensatorModel) {
		this.compensatorModel = compensatorModel;
	}
	
	public List<PrimaryEquipmentLedger> getSelectedLedgerList() {
		return selectedLedgerList;
	}


	public void setSelectedLedgerList(List<PrimaryEquipmentLedger> selectedLedgerList) {
		this.selectedLedgerList = selectedLedgerList;
	}


	public PrimaryEquipmentLedger getEditLedger() {
		return editLedger;
	}


	public void setEditLedger(PrimaryEquipmentLedger editLedger) {
		this.editLedger = editLedger;
	}


	public List<PrimaryEquipmentLedger> getSubstationModel() {
		return substationModel;
	}


	public void setSubstationModel(List<PrimaryEquipmentLedger> substationModel) {
		this.substationModel = substationModel;
	}


	public boolean isDispatchStatus() {
		return dispatchStatus;
	}


	public void setDispatchStatus(boolean dispatchStatus) {
		this.dispatchStatus = dispatchStatus;
	}


	public SubstationLedger getQueryLedger() {
		return queryLedger;
	}


	public void setQueryLedger(SubstationLedger queryLedger) {
		this.queryLedger = queryLedger;
	}
	
	
}
